package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.domain.pojo.Clazz;
import com.itheima.domain.query.QueryParam;
import com.itheima.domain.vo.PageResult;
import com.itheima.exception.DeleteClazzException;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.StudentMapper;
import com.itheima.service.ClazzService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author:篍
 * @Date: 2025/07/10 18:57
 * @Description:
 */
@Service
public class ClazzServiceImpl implements ClazzService {

    @Autowired
    StudentMapper studentMapper;

    /**
     * 查询所有班级
     * @return
     */
    @Override
    public List<Clazz> findAllClazz() {
        return clazzMapper.findAllClazz();
    }

    @Override
    public Clazz findById(Integer id) {
        return clazzMapper.findById(id);
    }

    @Override
    public void updateClazz(Clazz clazz) {
        clazzMapper.updateClazz(clazz);
    }

    @Autowired
    ClazzMapper clazzMapper;




    /**
     * 添加班级，补全建立时间和更新时间
     * @param clazz
     */
    @Override
    public void addClazz(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.addClazz(clazz);
    }



    @Override
    public PageResult<Clazz> findClazz(QueryParam queryParam) {
        Integer page=queryParam.getPage();
        Integer pageSize=queryParam.getPageSize();
        PageHelper.startPage(page,pageSize);
        Page<Clazz> clazzs= clazzMapper.findClazz(queryParam);
        List<Clazz> clazzsResult = clazzs.getResult();
        LocalDate now = LocalDate.now();
        //补全班级状态
        for (Clazz clazz : clazzsResult) {
            if(clazz.getBeginDate().isAfter(now)){
                clazz.setStatus("未开班");
            }else if(clazz.getEndDate().isBefore(now)){
                clazz.setStatus("已结课");
            }else {
                clazz.setStatus("在读");
            }
        }
        return new PageResult<>(clazzs.getTotal(),clazzsResult);
    }


    /**
     * 根据id班级删除班级
     * @param id
     */
    @Override
    public void deleteClazzById(Integer id) {
        //判断要删除的班级中是否有学生
//        Integer count=
        long count=studentMapper.findStudentCountByClazzId(id);
        if(count>0){
            throw new DeleteClazzException("对不起，当前部门下有员工，不能直接删除！");
        }
        clazzMapper.deleteClazzById(id);
    }
}
